<template>
  <form class="wrapper">
    <div id="layout">
      <div class="zk"></div>
      <div id="header">
        <div class="infoNav">
          <ul>
            <li style="width: 84px;height: 103px">
              <img id="detailbtn" class="kspic"
                   style="width:74px;height:96px;border:none;margin-top:-7px;margin-right:10px;cursor:pointer"
                   src="@/assets/static/imgkaoing/blue.jpg" onerror="@/assets/static/imgkaoing/blue.jpg'">
            </li>
            <li style="font-size:14px;color:#044950;position:relative;top:-10px;">
              <!--<div style="height:20px;"><label>考&emsp;试&emsp;科&emsp; 目：</label><span id="ksmc"></span></div>-->
              <!-- 姓名 -->
              <div style="height:20px;"><label>姓&emsp;&emsp;&emsp;&emsp;&emsp;名：</label><span
                  id="ksxm">{{ nickname }}</span></div>
              <!-- 座位号 -->
              <div style="height:20px;"><label>座&emsp;&emsp;位&emsp;&emsp;号：</label><span
                  id="ksxb">001</span></div>
              <!-- 准考证号 -->
              <div style="height:20px;"><label>准&emsp;考&emsp;证&emsp;号：</label><span
                  id="zkzh2">{{ idCard }}</span></div>
              <!-- 身份证号 -->
              <div style="height:20px;"><label>有效身份证件号：</label><span
                  id="sfzh">{{ idNumber }}</span></div>
            </li>
          </ul>
        </div>
        <div class="clockNav">
          <ul>
            <li class="clockNav_m">
              <!-- 考试倒计时 -->
              <div style="font-size:18px;color:red;font-weight:normal;">
                考试剩余时间:&nbsp;<span id="clock" ref="countDownRef">00:00:00</span>
              </div>
              <div style="margin-top:7px;font-size:16px;text-align:center">
									<span style="color:#044950;">未答:&nbsp;
                                        <span id="notPaperCount"
                                              style="color:red;">{{ maxQuestionIndex - answerQuestionCount }}</span>&nbsp;道
                                    </span>
                <span style="color:#044950;">已答:&nbsp;
                                    <span id="completePaperCount" style="color:black;">{{ answerQuestionCount }}</span>&nbsp;道&nbsp;
                                </span>
              </div>
            </li>
          </ul>
        </div>
        <div class="subjectNav">
						<span id="projectName"
                  style="font-size:28px;font-weight:normal; color:#044950; letter-spacing: 6px"
                  class="prname">{{ exam.name }}</span>
          <br>
          <!--                    <span id="subjectName" style="color:#044950;font-size:24px;font-weight:normal;">基础科目</span>-->
        </div>
      </div>
      <div id="main">
        <div id="leftnav" style="width:384px; height: 100%" ref="leftNav">
          <!-- 注意事项 标题 -->
          <div class="submark" @click="isOpenTip = !isOpenTip" style="font-size:18px;height:20px;">
            <div id="desc" style="background-color:white;">
              <h6 style="margin:0px;margin-left:-4px;line-height:20px;text-align:center;background-color:#a1dbdf;cursor:pointer;">
                <span style="color:black;">注意事项</span>
                <span id="xy" style="color:#044950;">（点击可隐藏/展开）</span>
              </h6>
            </div>
          </div>
          <!-- 注意事项 详情 -->
          <transition name="mini">
            <div id="showOrHidden" v-show="isOpenTip" class="submark"
                 style="font-size:12px;line-height:14px;height:120px;background-color:#F2F2F2;">
              <table border="0" style="margin: 0; padding: 0;">
                <tbody>
                <tr>
                  <td style="vertical-align:top; font-size: 15px; line-height: 20px">1、</td>
                  <td style="font-size: 15px; line-height: 20px; text-align: left;">
                    题号右方的“*”符号代表该小题尚未选择答案。
                  </td>
                </tr>
                <tr>
                  <td style="vertical-align:top; font-size: 15px; line-height: 20px">2、</td>
                  <td style="font-size: 15px; line-height: 20px; text-align: left;">
                    题号右方的“?”符号代表该小题做过标记。
                  </td>
                </tr>
                <tr>
                  <td style="vertical-align:top; font-size: 15px; line-height: 20px">3、</td>
                  <td style="font-size: 15px; line-height: 20px; text-align: left;">选择选项的同时自动保存答案。
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </transition>
          <div id="itembar">
            <div id="papernav">
              <ul id="P-sj1" style="display: block;">
                <div class="subitem">
                  <!-- 题目选项 -->
                  <a v-for="item in questions" @click="selectQuestion(item)"
                     :class="item === selectData?'active_q':''" class="navs green1 question_sel_item"
                     style="text-decoration: none;line-height:35px;padding:3px;margin:3px 2px;border-radius: 3px; cursor:pointer;">
                    <span>{{ item.title }}</span>
                    <!-- 加span*是表示未做题 ，加span？是表示标记题 -->
                    <!-- 是否为未做题 -->
                    <span v-show="!item.isAnswer"
                          style="color: red;font-size:14px;line-height:24px;vertical-align:top"
                          class="icon_answer">*</span>
                    <!-- 是否标记 -->
                    <span v-show="item.isMark === true"
                          style="color: red;font-size:14px;line-height:24px;margin-left:-11px;vertical-align:bottom"
                          class="icon_mark">?</span>
                  </a>
                </div>
              </ul>
            </div>
          </div>
        </div>

        <div id="no_question_info" v-show="!curQuestion">本考试暂无相关的题目信息</div>

        <!-- 右侧题目详情 -->
        <div id="container">
          <div class="submitExam" @click="showSubmitTip" :style="isSubmit?'background: #ccc':''">完成考试</div>
          <!-- 题目内容 -->
          <div id="question_frame2" v-if="curQuestion">
            <div id="sjHtml"
                 style="padding-top:0px;margin-bottom:0px;margin-left:10px;border-bottom: 1px solid #ECECEC;">
              <div class="itemGroupTitle">每一道考题下面有A、B、C、D、E五个备选答案，请从中选择一个最佳答案。</div>
              <!-- 题的类型 多个题在一起的 -->
              <div class="itemArea" id="question_content">
                <p>第 <span class="itemName">{{ selectData.title }}</span> 题</p>

                <!-- 材料题展示区 -->
                <div class="material_wrapper" v-if="selectData.type === 2">
                  <div class="material_title">{{ selectData.material.label }}</div>
                  <div class="material_content" v-html="selectData.material.text"></div>
                </div>

                <!-- 材料题选项 -->
                <div class="itemTitle">
                  <button type="button" id="b-183" class="itemSubTitle itemSubTitle-active"
                          v-if="selectData.type === 2 && selectData.questions.length>1"
                          v-for="item in selectData.questions">{{ item.index }}
                  </button>
                </div>

                <div class="itemArea">
                  <div class="itemContext">
                    <label class="labelClss">
                      <span class="question_title" v-html="curQuestion.q"></span>
                    </label>
                    <!-- 题干音频播放区域 -->
                    <div class="item_audio" v-show="curQuestion.qp">
                      <audio :src="curQuestion.qp" controls="controls" ref="questionAudio">Your browser does not
                        support the
                        audio
                        element.
                      </audio>
                    </div>
                    <!-- 题干视频播放区域 -->
                    <div class="item_video" v-show="curQuestion.qv">
                      <video :src="curQuestion.qv" controls="controls" ref="questionVideo">Your browser does not
                        support the
                        video
                        element.
                      </video>
                    </div>
                  </div>
                  <!-- 题目选项集合 -->
                  <div class="choiceContext">
                    <label class="labelClss">
                      <div class="choiceXxList" style="margin-left: -12px;">
                        <div class="option_item" v-for="item in curQuestion.oa.opt">
                          <span class="choiceTitle" style="margin-left:25px;line-height:200%">{{ item.k }}.</span>
                          <span class="option_content" style="line-height:200%"
                                v-html="item.c"></span>
                        </div>
                      </div>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 底部选项 -->
          <div id="footer" v-if="curQuestion">
            <label for="testflag">
              <input :disabled="complete" name="testflag" id="testflag" type="checkbox"
                     style="width:16px;height:16px;vertical-align:middle;" @click="mark(curQuestion)"
                     :checked="curQuestion.mark === true"> 标记
            </label>
            &nbsp;
            <button id="prevbtn" name="上一题" type="button" style="font-weight:bold;" @click="prefQuestion">
              上一题
            </button>
            &nbsp;
            <!-- 将选项radio插入footer中 -->
            <div id="xxList">
              <div class="option_item"
                   v-for="item in curQuestion.oa.opt" @click="selectOption(item.k)">
                <input :type="curQuestion.t === 1?'radio':'checkbox'"
                       :disabled="complete" @click="selectOption(item.k)" ref="optionItem"
                       name="option_item"
                       :value="item.k"
                       :checked="curQuestion.userAnswer && curQuestion.userAnswer.indexOf(item.k)>=0">{{ item.k }}
              </div>
            </div>
            &nbsp;
            <button id="nextbtn" name="下一题" type="button" style="font-weight: bold;" @click="nextQuestion">
              下一题
            </button>
          </div>
          <!-- 调试 -->
          <button type="button" id="calculatorcaller" @click="showCalculatorFlag = true">计算器</button>
          <!-- 调试 -->
        </div>
        <!-- 调试 -->
        <!-- 机身 -->
        <div class="calculatorbody" v-show="showCalculatorFlag === true">
          <div class="calculatorname">计算器</div>
          <!-- 关闭按钮 -->
          <div class="closebtn" @click="showCalculatorFlag = false"></div>
          <!--显示屏和按钮-->
          <div class="screenbtn">
            <!--显示屏-->
            <div id="calculatorscreen" ref="calculatorscreen">{{ calculatorResult }}</div>
            <!--按钮区域-->
            <!--1、4、7、00-->
            <div style="width:54px; height:130px; float:left; margin-left:13px; color:blue">
              <div class="calculatorButtons" @click="calculator(1)">1</div>
              <div class="calculatorButtons" @click="calculator(4)">4</div>
              <div class="calculatorButtons" @click="calculator(7)">7</div>
              <div class="calculatorButtons" @click="calculator('00')">00</div>
            </div>
            <!--5、2、8、0-->
            <div style="width:54px; height:130px; float:left; color:blue">
              <div class="calculatorButtons" @click="calculator(2)">2</div>
              <div class="calculatorButtons" @click="calculator(5)">5</div>
              <div class="calculatorButtons" @click="calculator(8)">8</div>
              <div class="calculatorButtons" @click="calculator(0)">0</div>
            </div>
            <!--3、6、9、.-->
            <div style="width:54px; height:130px; float:left; color:blue">
              <div class="calculatorButtons" @click="calculator(3)">3</div>
              <div class="calculatorButtons" @click="calculator(6)">6</div>
              <div class="calculatorButtons" @click="calculator(9)">9</div>
              <div class="calculatorButtons" @click="calculator('.')">.</div>
            </div>
            <!--+、-、*、/-->
            <div style="width:54px; height:130px; float:left; color:red">
              <div class="calculatorButtons" @click="calculator('+')">+</div>
              <div class="calculatorButtons" @click="calculator('-')">-</div>
              <div class="calculatorButtons" @click="calculator('*')">*</div>
              <div class="calculatorButtons" @click="calculator('/')">/</div>
            </div>
            <!--C、=-->
            <div style="width:50px; height:130px; float:left; color:red">
              <div class="calculatorButtons" @click="clearCalculate()">C</div>
              <div class="equalityButton" @click="resultsCalculate()">=</div>
            </div>
          </div>
        </div>
        <!-- 调试 -->
      </div>
    </div>

    <!-- 交卷问答弹窗 -->
    <div class="submit_ask" v-show="tipWindow">
      <div class="ask_title">
        <span>温馨提示</span>
        <span class="close" @click="closeSubmitTip">X</span>
      </div>
      <div class="ask_content">
        <div class="tip_wrapper" v-if="noAnswerQuestionIds.length>0">
          <dl>
            <dt>您还有 {{ noAnswerQuestionIds.length }} 题未答</dt>
            <dd>{{ noAnswerQuestionIds.join(",") }}</dd>
          </dl>
        </div>
        <p>您确定交卷吗?交卷后将不能继续答题</p>
        <div class="button_wrapper">
          <div class="ask_button" @click="submitExam">确定</div>
          <div class="ask_button" @click="closeSubmitTip">取消</div>
        </div>
        <div class="ask_warning_wrapper">
          <div class="icon"></div>
          <div class="content">正在考试环节中,考试剩余时间为0时将自动交卷,请各位考生注意</div>
        </div>
      </div>
    </div>

    <div class="submit_result" v-show="resultWindow">
      <div class="ask_title">
        <span>本次测验结果</span>
        <span class="close" @click="resultWindow = false">X</span>
      </div>
      <div class="ask_content">

        <table border="1" cellpadding="0" cellspacing="0" class="result_table">
          <thead>
          <tr>
            <th>试题数</th>
            <th>答对</th>
            <th>答错</th>
            <th>未答</th>
            <th>总分</th>
            <th>得分</th>
            <th>正确率</th>
          </tr>
          </thead>
          <tbody>
          <tr>
            <td>{{ this.maxQuestionIndex }}</td>
            <td>{{ this.examResult.rightCount }}</td>
            <td>{{ this.maxQuestionIndex - this.examResult.rightCount }}</td>
            <td>{{ this.maxQuestionIndex - this.answerQuestionCount }}</td>
            <td>{{ this.examResult.totalScore }}</td>
            <td>{{ this.examResult.score }}</td>
            <td style="color: red">{{ parseInt((this.examResult.rightCount / this.maxQuestionIndex) * 10000) / 100 }}
              %
            </td>
          </tr>
          </tbody>
        </table>
        <div class="button_wrapper">
          <div class="ask_button large" @click="viewExamResult">查看答题情况</div>
          <div class="ask_button" @click="toHome">重考</div>
        </div>
      </div>
    </div>


  </form>
</template>

<script type="text/ecmascript-6">
import {examMixin} from "../mixins/mixin";
import {formatHTML} from "@/utils/common";
import {sha1} from "@/utils/sha1";
import {ref, onMounted} from 'vue';
import {countDownFormat} from "../utils/common";
import {submitQuestion} from "@/api/exam";

export default {
  data() {
    let idCard = this.getStore("idCard");
    let idNumber = this.getStore("idNumber");
    let loginUser = this.getStore("loginUser");

    return {
      //  是否显示计算器
      showCalculatorFlag: false,
      //  考试记录id
      viewId: null,
      //  考试唯一编号(sha1加密后)
      examId: null,
      //  当前题目集合(已经格式化的)
      questions: [],
      //  考试最终结果
      examResult: {},
      //  用户昵称
      nickname: loginUser.nickname,
      //  准考证号码
      idCard,
      //  身份证号码
      idNumber,
      //  如果在没有题目时,是否显示没有题目的提示
      isOpenTip: true,
      //  当前正在做的题目
      curQuestion: null,
      //  当前选中的题目所属的提级(一个题目有一个自己封装的提级,如果是材料题,则一个提级中可能存在多个题目)
      selectData: null,
      //  当前试卷的最大题目索引号
      maxQuestionIndex: 0,
      //  考试时间(分钟)
      time: 60,
      //  加入考试时间
      joinTime: null,
      //  定时器标记
      timer: null,
      //  判断考试是否已经完成
      complete: false,
      //  提交试卷时的弹窗是否显示标记
      tipWindow: false,
      //  当前试卷是否已提交
      isSubmit: false,
      //  考试结果弹窗是否显示标记
      resultWindow: false,
      //  计算器显示屏数字
      calculatorResult: "",
      calculatorReset: false,
    }
  },
  setup() {
    let optionItem = ref(null);
    let countDownRef = ref(null);
    let calculatorscreen = ref(null);
    let questionVideo = ref(null);
    let questionAudio = ref(null);
    let leftNav = ref(null);
    return {
      optionItem,
      countDownRef,
      calculatorscreen,
      questionVideo,
      questionAudio,
        leftNav
    };
  },
  computed: {
    //  题目总数量
    answerQuestionCount() {
      let count = 0;
      this.questions.forEach(item => {
        item.questions.forEach(question => {
          if (question.userAnswer && question.userAnswer.length > 0) count += 1;
        })
      })
      return count;
    },
    //  未答题数量
    noAnswerQuestionIds() {
      let collect = [];
      this.questions.forEach(item => {
        item.questions.forEach(question => {
          if (!question.userAnswer || question.userAnswer.length === 0) collect.push(question.index);
        })
      });
      return collect;
    },
  },
  mixins: [examMixin],
  async created() {
    //  验证考试的参数
    this.checkExamParams();
    //  获取考试题目
    let result = this.getStore("questionsResult");
    if (!result) {
      //  如果当前考试的题目不存在,则跳转到首页重新选择考试目录
      this.$router.push("/");
    }
    this.viewId = result.id;
    //  当前考试的唯一表示
    this.examId = sha1(result.no + "_" + result.item_no);
    //  构建题目集合
    this.questions = this.buildResult(result);
    //  默认选中第一题selectQue
    if (this.questions[0]) this.selectQuestion(this.questions[0]);

    //  判断当前试卷是否已提交
    this.isSubmit = this.getStore("submit_answer_" + this.examId);
    //  如果已经交卷,则无法再做题
    if (this.isSubmit === true) {

      //  标注考试为完成状态
      this.complete = true;
      //  解析得到考试结果
      this.examResult = this._buildSubmitParams();
      //  显示考试结果界面
      this.resultWindow = true;
    }

    //  设置考试时间
    this.time = result.test_time;
    //  得到加入考试时间
    this.joinTime = this.getStore("joinTime");
    if (!this.joinTime) {
      this.setStore("joinTime", new Date());
      this.joinTime = this.getStore("joinTime");
    }

    //  元素加载完成后,计算考试倒计时
    onMounted(() => {
        this.resetLeftNavHeight();
      //  如果还未交卷,则
      this.timer = setInterval(() => {
        let flag = this.countDownFunc();
        if (!flag) {
          //  如果考试时间到期,则不允许再做题
          this.computed = true;
          //  清空定时器
          clearInterval(this.timer);
          //  自动交卷
          this.submitExam();
        }
      }, 1000);
    });

    window.onresize = ()=>{
        this.resetLeftNavHeight();
    }

  },
  methods: {
      resetLeftNavHeight(){
          if(!this.leftNav)return;
          let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
          let height = clientHeight- 125;
          this.leftNav.style.height = height+"px";
      },
    //  点击计算器按钮操作
    calculator(keyPress) {
      this.calculatorResult += keyPress;
    },
    //  计算计算器中的结果
    resultsCalculate() {
      this.calculatorResult = eval(this.calculatorResult);
      this.calculatorReset = true;
    },
    //  清空计算器显示屏
    clearCalculate() {
      this.calculatorResult = "";
    },
    //  考试倒计时
    countDownFunc() {
      //  考试倒计时计算
      let joinTime = this.joinTime;
      if (typeof joinTime === "string") joinTime = new Date(joinTime);
      let endTime = new Date();
      endTime.setTime(joinTime.getTime() + (this.time * 1000));
      let diffTime = parseInt((endTime - new Date().getTime()) / 1000);
      let timeText = countDownFormat(diffTime);
      if (this.countDownRef) this.countDownRef.innerText = timeText;
      if (timeText === "00:00:00") {
        //  考试到期,显示答案并提交试卷
        return false;
      }
      return true;
    },
    //  初始化考试题目
    buildResult(result) {
      let materialData = result.qd && result.qd[1] ? result.qd[1] : [],
          questions = result.questions;
      let formatQuestions = [];
      //  题号索引
      let index = 1;

      //  当前缓存的已做过的答题
      let storeAnswer = this.getAnswer();
      //  当前缓存的已标记的答题
      let storeMark = this.getMark();
      //  格式化普通题目
      questions.forEach(item => {
        let questionItem = {
          //  题号标题,1,2,3-6
          title: index,
          //  类型,1:普通题目,2:材料题
          type: item.t,
          isAnswer: false,
          //  题目集合
          questions: []
        };

        //  设置已做的题目
        if (storeAnswer[item.id]) {
          questionItem.isAnswer = true;
          item.userAnswer = storeAnswer[item.id];
        }

        //  设置已标记的题目
        if (storeMark[item.id]) {
          questionItem.isMark = true;
          item.mark = storeMark[item.id];
        }

        if (item.t === 1) {
          //  如果是普通题目,则直接加入到题目集合中
          item.index = index;
          questionItem.questions.push(item);
          formatQuestions.push(questionItem);
          index += 1;
        } else {
          //  如果是材料题,则增加到材料题的题目集合中
          if (materialData[item.qd]) {
            let material = materialData[item.qd];
            if (material.questions == null) material.questions = [];
            material.questions.push(item);
          }
        }
      });
      //  归类材料题
      materialData.forEach(item => {
        //  如果当前材料没有题目,则直接返回
        if (!item.questions) return null;
        let questionItem = {
          type: 2,
          isAnswer: false,
          questions: [],
          material: {
            label: item.label,
            text: formatHTML(item.text)
          }
        };
        //  题号起始位置
        let startFlag = index;
        item.questions.forEach(question => {
          if (question.userAnswer) questionItem.isAnswer = true;
          if (question.mark) questionItem.isMark = true;
          question.index = index;
          questionItem.questions.push(question);
          index += 1;
        });
        //  判断题号标题
        questionItem.title = (startFlag + 1) === index ? index - 1 : (startFlag) + "-" + index - 1;

        formatQuestions.push(questionItem);
      });
      this.maxQuestionIndex = index - 1;
      return formatQuestions;
    },
    //  选中某个题目时
    selectQuestion(data, index = 0) {
      //  如果所选择的是当前题目,则直接返回
      if (this.curQuestion && this.curQuestion.index === index) return false;
      this.selectData = data;
      let curQuestion = data.questions[index];
      //  格式化替换题目中的html
      curQuestion.q = formatHTML(curQuestion.q);
      if (curQuestion.oa && curQuestion.oa.opt) {
        curQuestion.oa.opt.forEach(item => {
          item.c = formatHTML(item.c);
        });
      }
      this.curQuestion = curQuestion;
    },
    //  选中某个选项时
    selectOption(answer) {
      //  如果考试已到期或已交卷,则无法再做题
      if (this.complete) return false;

      //  获取考生答案
      let answerCollection = [];
      this.optionItem.forEach(item => {
        if (item.checked) {
          answerCollection.push(item.value);
        }
      });
      //  设置当前题目的考生答案
      this.curQuestion.userAnswer = answerCollection;

      //  标记题目角标是否已做题
      let searchFlag = true;
      this.selectData.questions.forEach(item => {
        if (!item.userAnswer || item.userAnswer.length === 0) searchFlag = false;
      });
      this.selectData.isAnswer = searchFlag;
      this.setAnswerByItem(this.curQuestion.id, this.curQuestion.userAnswer);
    },
    //  根据序号获取题目
    selectQuestionByIndex(index) {
      this.questions.forEach(item => {
        let itemIndex = 0;
        item.questions.forEach(question => {
          if (question.index === index) {
            this.selectQuestion(item, itemIndex);
          }
          itemIndex += 1;
        })
      })
    },
    //  获取上一题
    prefQuestion() {
      let curIndex = this.curQuestion.index;
      if (curIndex === 1) return false;
      this.selectQuestionByIndex(curIndex - 1);
    },
    //  获取下一题
    nextQuestion() {
      let curIndex = this.curQuestion.index;
      if (curIndex === this.maxQuestionIndex) return false;
      this.selectQuestionByIndex(curIndex + 1);
    },
    //  标记题目
    mark(question) {
      question.mark = !question.mark ? true : false;
      this.selectData.isMark = question.mark;
      this.setMarkByItem(question.id, question.mark);
    },
    //  获取保存的标记信息
    getMark() {
      let mark = this.getStore("mark_" + this.examId);
      if (!mark) mark = {};
      return mark;
    },
    //  保存当前题目标记
    setMarkByItem(questionId, answer) {
      let storeMark = this.getMark();
      storeMark[questionId] = answer;
      this.setStore("mark_" + this.examId, storeMark);
    },
    //  获取当前试卷的题目
    getAnswer() {
      let answer = this.getStore("answer_" + this.examId);
      if (!answer) answer = {};
      return answer;
    },
    //  保存当前试卷答案
    setAnswerByItem(questionId, answer) {
      let storeAnswer = this.getAnswer();
      storeAnswer[questionId] = answer;
      this.setStore("answer_" + this.examId, storeAnswer);
    },
    //  打开交卷弹窗
    showSubmitTip() {
      if (!this.isSubmit) this.tipWindow = true;
      this.complete = true;
    },
    //  关闭交卷弹窗
    closeSubmitTip() {
      this.tipWindow = false;
      this.complete = false;
      this.countDownFunc();
    },
    toHome() {
      let resultQuestions = this.getStore("questionsResult");
      this.$router.push(`/join?no=${resultQuestions.no}&item_no=${resultQuestions.item_no}`);
    },
    //  跳转到考试结果查看界面
    viewExamResult() {
      console.log("查看考试详情");
      let resultQuestions = this.getStore("questionsResult");
      this.$router.push(`/viewExam?no=${resultQuestions.no}&item_no=${resultQuestions.item_no}&id=${resultQuestions.id}`);
      // http://127.0.0.1:8001/realexam/#/join?no=qv39&item_no=pt134
    },
    //  提交试卷
    async submitExam() {
      //  标记考试为完成状态
      this.complete = true;
      //  得到考试结果
      this.examResult = this._buildSubmitParams();
      let requestParams = this.examResult;
      requestParams.answer = JSON.stringify(requestParams.answer);

      if (this.isSubmit !== true) {
        //  发送服务器保存考试结果
        let response = await submitQuestion(requestParams);
        if (response === 0) {
          //  关闭考试交卷弹窗
          this.tipWindow = false;
          //  设置当前考试为已提交状态
          this.isSubmit = true;
          //  保存考试已提交状态
          this.setStore("submit_answer_" + this.examId, true);
          // alert("保存成功");
        } else {
          alert("保存失败: " + response.msg);
        }
      }
      //  显示考试成绩
      this.resultWindow = true;
    },
    //  得到考试结果,构建服务器请求数据
    _buildSubmitParams() {
      //  得到试卷信息
      let questionResult = this.getStore("questionsResult");

      //  得到考试时间
      let examTime = parseInt((new Date().getTime() - new Date(this.joinTime).getTime()) / 1000);
      //  如果当前时间超过了交卷时间,则使用最大时间
      if (examTime > (this.time * 60)) examTime = this.time * 60;

      //  服务器请求参数
      let params = {
        id: questionResult.id,
        no: questionResult.no,
        item_no: questionResult.item_no,
        answer_time: examTime,
        answer: {},

        //  答题正确数量
        rightCount: 0,
        //  试卷总分
        totalScore: 0,
        //  试卷得分
        score: 0
      };

      //  遍历所有题目
      this.questions.forEach(item => {
        item.questions?.forEach(question => {
          //  计算总分
          params.totalScore += question.score;
          //  判断当前答题是否正确
          let isRight = false;
          if (question.userAnswer) isRight = question.oa.a.sort().toString() === question.userAnswer.sort().toString();

          //  如果答对,则增加对题数量以及考试分数
          if (isRight) {
            params.rightCount += 1;
            params.score += question.score;
          }
          params.answer[question.id] = {
            //  得分
            s: isRight ? question.score : 0,
            //  考生答案
            a: question.userAnswer ? question.userAnswer : [],
            //  类型
            t: question.t
          };
        });
      });

      return params;
    },

  }
};


</script>
<style src="@/assets/static/imgkaoing/exam.css" scoped/>
<style src="@/assets/static/imgkaoing/style.css" scoped/>
<style src="@/assets/static/imgkaoing/item.css" scoped/>
<style lang="stylus" rel="stylesheet/stylus">
.submit_result
.submit_ask
  position: absolute
  width: 500px
  border-radius 5px
  top: 35%;
  left: 50%;
  margin-left: -250px;
  font-weight bold
  font-family "宋体"

.item_audio
  audio
    display: block !important;

.item_video
  max-height: 300px
  max-width: 500px;
  video
    max-width: 500px;
    max-height: 300px;

.submit_ask
.submit_result
  .ask_title
    height: 60px
    line-height 60px
    text-align center
    color #FFffff
    font-size 20px
    background rgb(16, 100, 111)
    cursor default
    position relatives
    text-align center

    .close
      position absolute
      right 20px
      top 0
      cursor pointer

  .ask_content
    padding: 10px 40px
    background #FFffff

    .tip_wrapper
      color rgb(170, 170, 170)

      dt
        margin: 10px 0;

      dd
        color red
        white-space nowrap
        text-overflow ellipsis
        overflow hidden
        font-size 16px

    p
      text-align center
      margin: 15px

    .button_wrapper
      width: 80%;
      margin: 20px auto

      .ask_button
        width: 100px
        text-align center
        display inline-block
        line-height 40px
        background rgb(63, 146, 150)
        border-radius 5px
        color #FFffff
        cursor pointer

        &.large
          width: 150px;

        &:last-child
          float right

    .ask_warning_wrapper
      color red

.submit_result
  width: 600px

.submitExam
  width: 110px;
  height: 40px;
  line-height: 40px;
  border-radius 3px;
  background: rgb(255, 130, 111)
  text-align: center;
  cursor: pointer;
  position: absolute
  right: 110px;
  color: #FFffff
  font-weight bold

.active_q
  background: rgba(161, 219, 223, 1) !important

.question_sel_item
  position: relative

  .icon_answer
    position: absolute
    top: 0
    right: 0

  .icon_mark
    position: absolute
    bottom: -5px
    right: 0

.question_title, .material_content, .option_item
  display: block;

  img
    vertical-align middle

#container
  height: 100%
  width: 100%

.material_wrapper
  padding: 15px;
  min-height: 100px;

  .material_title
    line-height: 25px;
    font-weight: bold

  .material_content
    margin-left: 20px;

#no_question_info
  position: fixed
  left: 50%;
  top: 50%;
  width: 200px;
  text-align center
  margin-top: -10px;
  line-height: 20px;

#question_content
  position: absolute
  left: 390px;
  right: 0;
  top: 80px;
  bottom: 165px;
  overflow-y: scroll

body
  border: 1px solid transparent
  background: url(@/assets/static/imgkao/background.jpg) repeat-x;

#xxList
  display: inline-block

  .option_item
    display: inline-block
    margin: 10px;
    cursor: pointer

.wrapper
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  text-align: left
  font-family: "宋体"

&.mini-enter-active, &.mini-leave-active
  transition: all 0.4s ease

&.mini-enter, &.mini-leave-to
  height: 0 !important;
  overflow: hidden

.result_table
  border: 1px solid #f0f0f0
  width: 100%
  text-align: center
  line-height: 30px
</style>
